package com.engineering.elink.service.impl;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.engineering.elink.common.ErrorType;
import com.engineering.elink.domain.CourseType;
import com.engineering.elink.service.CourseTypeService;
import com.engineering.elink.util.CollectionUtil;
import com.engineering.elink.util.ResJsonUtil;
import com.engineering.elink.videodao.CourseMapper;
import com.engineering.elink.videodao.CourseTypeMapper;
import com.fasterxml.jackson.core.type.TypeReference;

@Service
public class CourseTypeServiceImpl implements CourseTypeService{

	@Autowired
	private CourseTypeMapper courseTypeMapper;
	
	@Autowired
	private CourseMapper courseMapper;
	
	@Override
	public List<CourseType> getCourseType() {
		return courseTypeMapper.selectList();
	}

	@Override
	public Map<String, Object> deleteCourseType(Integer typeId) {
		
		CourseType type=courseTypeMapper.selectByPrimaryKey(typeId);
		if(type!=null){
			//批量更新课程
			int count=courseMapper.updateCourseByType(typeId);
	
			//删除分类
			count=courseTypeMapper.deleteByPrimaryKey(typeId);
			if(count<=0){
				return ResJsonUtil.getMap(ErrorType.DELETE_COURSETYPE_ERROR);
			}
			return ResJsonUtil.getMap(ErrorType.SUCCESS);
		}
		
		return ResJsonUtil.getMap(ErrorType.COURSETYPE_ERROR);
	}

	@Override
	public Map<String, Object> updateCourseType(String jsonStr) {
		
		List<CourseType> list=JsonBinderUtil.fromJsontolist(jsonStr,new TypeReference<List<CourseType>>(){});
		
		if(CollectionUtil.collectionIsNotEmpty(list)){
			for(CourseType type:list){
				if(type==null)continue;
				if(type.getId().intValue()==0){
					type.setId(null);
					courseTypeMapper.insertSelective(type);
				}else{
					courseTypeMapper.updateByPrimaryKeySelective(type);
				}
			}
			return ResJsonUtil.getMap(ErrorType.SUCCESS);
		}
		
		return ResJsonUtil.getMap(ErrorType.REQUEST_PARAMS_ERROR);
	}

}
